package com.qingyun.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokActivityTag;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokTag;
import com.qingyun.shop.domain.TiktokTagToBgm;
import com.qingyun.shop.domain.bo.tag.TiktokTagAddBo;
import com.qingyun.shop.domain.bo.tag.TiktokTagBo;
import com.qingyun.shop.domain.bo.tag.TiktokTagEditBo;
import com.qingyun.shop.domain.vo.TiktokTagSelectListVo;
import com.qingyun.shop.domain.vo.TiktokTagVo;
import com.qingyun.shop.mapper.TiktokActivityTagMapper;
import com.qingyun.shop.mapper.TiktokShopMapper;
import com.qingyun.shop.mapper.TiktokTagMapper;
import com.qingyun.shop.mapper.TiktokTagToBgmMapper;
import com.qingyun.shop.service.ITiktokTagService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 标签Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-26
 */
@Service
@AllArgsConstructor
public class TiktokTagServiceImpl extends ServicePlusImpl<TiktokTagMapper, TiktokTag, TiktokTagVo> implements ITiktokTagService {

    private final TiktokShopMapper shopMapper;

    private final MapperFacade mapperFacade;

    private final TiktokTagToBgmMapper tagToBgmMapper;

    private final TiktokActivityTagMapper activityTagMapper;

    @Override
    public TiktokTagVo queryById(Long tId) {
        TiktokTag tag = baseMapper.selectById(tId);
        TiktokTagVo result = mapperFacade.map(tag, TiktokTagVo.class);
        if (result.getIsDefault() == 0) {
            result.setShopName("平台");
        } else {
            result.setShopName(shopMapper.selectById(result.getShopId()).getName());
        }
        return result;
    }

    @Override
    public TableDataInfo<TiktokTagVo> queryPageList(TiktokTagBo bo) {
        if (!SecurityUtils.isManager()) {
            bo.setShopId(SecurityUtils.getSysLoginUser().getShop().getId());
        }

        PagePlus<TiktokTag, TiktokTagVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));

        result.getRecordsVo().forEach(t -> {
            if (t.getIsDefault() == 0) {
                t.setShopName("平台");
            } else {
				TiktokShop tiktokShop = shopMapper.selectById(t.getShopId());
				if (ObjectUtil.isNotNull(tiktokShop)) {
					t.setShopName(tiktokShop.getName());
				}else{
					t.setShopName("无");
				}

            }
        });

        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TiktokTagVo> queryList(TiktokTagBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TiktokTag> buildQueryWrapper(TiktokTagBo bo) {
        LambdaQueryWrapper<TiktokTag> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTagName()), TiktokTag::getTagName, bo.getTagName());
        if (!SecurityUtils.isManager()) {
            lqw.in(TiktokTag::getShopId, 0L, bo.getShopId());
        } else {
            lqw.eq(bo.getShopId() != null, TiktokTag::getShopId, bo.getShopId());
        }
        lqw.eq(bo.getStatus() != null, TiktokTag::getStatus, bo.getStatus());
        lqw.eq(bo.getIsDefault() != null, TiktokTag::getIsDefault, bo.getIsDefault());
        lqw.eq(bo.getTagType() != null, TiktokTag::getTagType, bo.getTagType());
        lqw.orderByDesc(TiktokTag::getStatus, TiktokTag::getShopId);
        return lqw;
    }

    @Override
    public Boolean insertByBo(TiktokTagAddBo bo) {
        TiktokTag tag = BeanUtil.toBean(bo, TiktokTag.class);

        if (SecurityUtils.isManager()) {
            tag.setIsDefault(0);
            tag.setShopId(0L);
        } else {
            Long shopId = Objects.requireNonNull(SecurityUtils.getShop()).getId();
            tag.setShopId(shopId);
        }
        return save(tag);
    }

    @Override
    public Boolean updateByBo(TiktokTagEditBo bo) {
        TiktokTag update = BeanUtil.toBean(bo, TiktokTag.class);

        TiktokTag tag = baseMapper.selectById(update);

        if (!SecurityUtils.isManager() && tag.getIsDefault() == 0) {
            throw new ServiceException("您不能修改平台创建的标签");
        }

        return updateById(update);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {

        List<TiktokTag> tiktokTags = this.baseMapper.selectBatchIds(ids);

        tiktokTags.forEach(t -> {
            if (t.getIsDefault() == 0 && !SecurityUtils.isManager()) {
                throw new ServiceException("【" + t.getTagName() + "】 为平台创建不可删除，您可以选择禁用此标签");
            }
            baseMapper.deleteById(t);
        });
        ids.forEach(t -> {
				tagToBgmMapper.delete(Wrappers.query(new TiktokTagToBgm().setTagId(t)));
				activityTagMapper.delete(Wrappers.query(new TiktokActivityTag().setTagId(t)));
			});


        return Boolean.TRUE;
    }

    @Override
    public List<TiktokTagSelectListVo> getSelectTags() {

        if (SecurityUtils.isManager()) {
            return baseMapper.getSelectTags(0L);
        }

        Long sid = SecurityUtils.getSysLoginUser().getShop().getId();
        return baseMapper.getSelectTags(sid);
    }
}
